import { merchantLoginPath } from '@/config';
import merchantManagerShopApi from '@/pages/MerchantManager/Shop/request';
import useRouter from '@/utils/useRouter';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { ConfigProvider, Form } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { useModel } from 'umi';
import style from './index.less';
import api from './request';

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [, setImageCode] = useState<UserApi.ImageCodeResponse>({ codeid: '', image: '' });

  const router = useRouter();
  const [form] = Form.useForm();

  const getCodeRequest = async () => {
    const data = await api.getCode();
    if (data) setImageCode(data);
  };
  const loginRequest = async (params: UserApi.LoginParams) => {
    const data = await api.login(params);
    if (data && initialState) {
      const { token, userId } = data;
      window.localStorage.setItem('access_token', token);
      window.localStorage.setItem('user_id', userId);
      const userInfo = await initialState.getUserInfo({ id: userId });

      const { roleDepartmentLists } = userInfo;
      if (roleDepartmentLists && roleDepartmentLists.length) {
        const roleDepartment = roleDepartmentLists[0];
        const { groupID, subsidiaryID, departmentId, userRoleId } = roleDepartment;
        Object.assign(userInfo, { groupID, subsidiaryID, departmentId, userRoleId });
      }

      const authMenu = await initialState.getAuthMenu({ RoleId: userInfo.userRoleId });
      flushSync(() => setInitialState((s) => ({ ...s, userInfo, authMenu } as any)));

      window.localStorage.setItem('user_info', JSON.stringify(userInfo));

      router.push('/organization/group-base-management');
    } else {
      form.setFieldValue('code', '');
      getCodeRequest();
    }
  };
  const merchantloginRequest = async (params: MerchantManagerShopApi.LoginParams) => {
    const data = await merchantManagerShopApi.login(params);

    if (data && initialState) {
      const { token, userId, shopId } = data;
      window.localStorage.setItem('access_token', token);
      window.localStorage.setItem('user_id', userId);
      const userInfo = await initialState.getMerchantUserInfo({});

      flushSync(() => setInitialState((s) => ({ ...s, userInfo, authMenu: [] } as any)));

      window.localStorage.setItem('user_info', JSON.stringify(userInfo));

      router.push(`/merchant-manager/shop/${shopId}`);
    }
  };
  const submit = async (values: UserApi.LoginParams) => {
    const { location } = history;
    if (location.pathname === merchantLoginPath) {
      const params: MerchantManagerShopApi.LoginParams = { ...values };
      merchantloginRequest(params);
    } else {
      const params: UserApi.LoginParams = { ...values };
      loginRequest(params);
    }
  };

  useEffect(() => {
    // getCodeRequest();
  }, []);
  const currentYear = new Date().getFullYear();
  return (
    <div className={style.login}>
      <div className={style.left}>
        <div className={style.logo}>{/* <img alt="logo" src="/logo.svg" /> */}</div>
      </div>
      <div className={style.right}>
        <div className={style.title}>深圳市九鑫信息科技有限公司</div>
        <div className={style.footer}>
          <div> {`© Copyright 版权所有：${currentYear} All Rights Reserved.`}</div>
          <div>
            深圳市九鑫信息科技有限公司
            <a href="https://beian.miit.gov.cn/">粤ICP备2023117415号-1</a>
          </div>
        </div>
        <div className={style.formBox}>
          <div className={style.formTitle}>
            <p>{location.pathname.includes(merchantLoginPath) ? '商家' : '系统'}登录</p>
            <span>
              {location.pathname.includes(merchantLoginPath) ? 'MERCHANT' : 'SYSTEM'} LOGIN
            </span>
          </div>
        </div>
        <div className={style.form}>
          <ConfigProvider theme={{ token: { colorPrimary: '#1890ff' } }}>
            <LoginForm
              contentStyle={{
                minWidth: 360,
                maxWidth: '75vw',
              }}
              initialValues={{}}
              actions={[]}
              form={form}
              onFinish={submit}
            >
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码',
                  },
                ]}
              />
              {/* <div className={style.loginItem}>
                <ProFormText
                  name="code"
                  fieldProps={{
                    size: 'large',
                    prefix: <VerifiedOutlined />,
                  }}
                  placeholder="验证码"
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码',
                    },
                  ]}
                />
                {imageCode.image && (
                  <img src={`data:image/png;base64,${imageCode.image}`} onClick={getCodeRequest} />
                )}
              </div> */}
            </LoginForm>
          </ConfigProvider>
        </div>
      </div>
      {/* <div className={style.loginBox}></div> */}
    </div>
  );
};

export default Login;
